package cz.vse.javaee.album;

import javax.ejb.*;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;

/**
 *
 * <p/>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Mar 15, 2010
 * Time: 2:31:10 PM
 */
@Stateful
@LocalBean
@TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
public class PhotoGateway {

    private Photo photo;

    /**
     * In the case of a container-managed persistence context that is scoped to a single transaction,
     * the persistence context ends when an associated transaction commits or is rolled back through
     * the Java Transaction API (JTA). By comparison, a container-managed persistence context that
     * has an <b>extended</b> lifetime begins when a stateful session bean is created and ends only when
     * the stateful session bean is removed from the container. The extended persistence context
     * is said to be bound to the stateful session bean. Note that only stateful session beans
     * can have a container-managed, extended entity manager.
     */
    @PersistenceContext(unitName = "album", type = PersistenceContextType.EXTENDED)
    private EntityManager entityManager;

    public Photo find(String photoName) throws NoPhotoFoundException {
        Query query = entityManager.createNamedQuery(AlbumDAOBean.PHOTO_BY_NAME);
        query.setParameter("name", photoName);
        photo = (Photo) query.getSingleResult();
        return photo;
    }

    public Photo getCurrent() {
        return photo;
    }

    public void refresh() {
        entityManager.refresh(photo);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    @Interceptors(CacheSynchronizer.class)
    public void save() {
    }

    @Remove
    public void closeGate() {
        System.out.println("Closing photo gate");
    }
}
